import { useState } from 'react';
import { ExecutionRecord } from './types';

interface TaskHistoryProps {
  tasksByCategory: { [key: string]: ExecutionRecord[] };
}

export const TaskHistory = ({ tasksByCategory }: TaskHistoryProps) => {
  const [expandedCategories, setExpandedCategories] = useState<string[]>([]);
  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest'>('newest');
  const [showLimit, _] = useState<number>(3);

  // 切换分类的展开/折叠状态
  const toggleCategory = (category: string) => {
    setExpandedCategories(prev => 
      prev.includes(category)
        ? prev.filter(c => c !== category)
        : [...prev, category]
    );
  };

  // 渲染单个任务卡片
  const renderTaskCard = (task: ExecutionRecord) => (
    <div
      key={task.id}
      className={`p-4 rounded-lg ${
        task.status === 'success' 
          ? 'bg-green-50 dark:bg-green-900/20' 
          : 'bg-red-50 dark:bg-red-900/20'
      }`}
    >
      <div className="flex justify-between items-start mb-2">
        <div className="flex items-center gap-2">
          <span className={task.status === 'success' ? 'text-green-500' : 'text-red-500'}>
            {task.status === 'success' ? '✓' : '✕'}
          </span>
          <h3 className="font-medium dark:text-gray-200">{task.taskTitle}</h3>
          <span className={`px-2 py-0.5 rounded text-sm ${
            task.status === 'success' 
              ? 'bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300'
              : 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300'
          }`}>
            {task.status === 'success' ? '成功' : '错误'}
          </span>
        </div>
        <div className="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
          <span>{new Date(task.createdAt).toLocaleString()}</span>
          <span>用时：{task.duration}</span>
          <button className="flex items-center gap-1 hover:text-blue-500 dark:hover:text-blue-400">
            <span>↻</span>
            重新运行
          </button>
        </div>
      </div>
      <p className="text-gray-600 text-sm dark:text-gray-400">{task.taskGuide}</p>
      {task.error && (
        <p className="mt-2 text-sm text-red-600 dark:text-red-400">错误：{task.error}</p>
      )}
    </div>
  );

  // 获取按最近更新排序的分类
  const getSortedCategories = () => {
    
    return Object.entries(tasksByCategory)
      .map(([category, tasks]) => ({
        category,
        latestUpdate: Math.max(...tasks.map(t => t.createdAt.getTime()))
      }))
      .sort((a, b) => b.latestUpdate - a.latestUpdate)
      .map(item => item.category);
  };

  // 获取要显示的前五个分类
  const displayedCategories = getSortedCategories().slice(0, showLimit);
  
  // 总分类数
  const totalCategoryCount = Object.keys(tasksByCategory).length;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
      <div className="p-6">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-semibold flex items-center dark:text-white">
            <span className="mr-2">⏱</span>
            任务历史记录
          </h2>
          <div className="flex items-center gap-4">
            <button
              onClick={() => setExpandedCategories(
                expandedCategories.length === displayedCategories.length
                  ? []
                  : [...displayedCategories]
              )}
              className="text-sm text-blue-500 hover:text-blue-600 dark:text-blue-400"
            >
              {expandedCategories.length === displayedCategories.length ? '全部折叠' : '全部展开'}
            </button>
            <select 
              className="border rounded-md px-3 py-1 text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
              value={sortOrder}
              onChange={(e) => setSortOrder(e.target.value as 'newest' | 'oldest')}
            >
              <option value="newest">最新</option>
              <option value="oldest">最早</option>
            </select>
          </div>
        </div>

        <div className="space-y-3">
          {displayedCategories.map(category => {
            const tasks = tasksByCategory[category];
            const sortedTasks = [...tasks].sort((a, b) => 
              sortOrder === 'newest' 
                ? b.createdAt.getTime() - a.createdAt.getTime()
                : a.createdAt.getTime() - b.createdAt.getTime()
            );
            
            return (
              <div key={category} className="border dark:border-gray-700 rounded-lg overflow-hidden">
                <button
                  onClick={() => toggleCategory(category)}
                  className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-700 flex items-center justify-between hover:bg-gray-100 dark:hover:bg-gray-600"
                >
                  <div className="flex items-center gap-2">
                    <span className="text-gray-600 dark:text-gray-300 font-medium">{category}</span>
                    <span className="text-sm text-gray-500 dark:text-gray-400">({tasks.length})</span>
                    {tasks.some(task => task.status === 'error') && (
                      <span className="px-2 py-0.5 rounded text-xs bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300">
                        有错误
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-500 dark:text-gray-400">
                      最近更新: {new Date(Math.max(...tasks.map(t => t.createdAt.getTime()))).toLocaleDateString()}
                    </span>
                    <span 
                      className={`transform transition-transform duration-200 ${
                        expandedCategories.includes(category) ? 'rotate-180' : ''
                      }`}
                    >
                      ▼
                    </span>
                  </div>
                </button>
                <div 
                  className={`transition-all duration-200 ${
                    expandedCategories.includes(category)
                      ? 'max-h-[1000px] opacity-100'
                      : 'max-h-0 opacity-0'
                  } overflow-hidden`}
                >
                  <div className="p-4 space-y-4 bg-white dark:bg-gray-800">
                    {sortedTasks.map(task => renderTaskCard(task))}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {totalCategoryCount === 0 ? (
          <div className="text-center text-gray-500 dark:text-gray-400 py-8">
            暂无历史记录
          </div>
        ) : totalCategoryCount > showLimit && (
          <div className="mt-6 text-center">
            <a 
              href="/history" 
              className="inline-block px-4 py-2 bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 rounded-md hover:bg-blue-200 dark:hover:bg-blue-800/40 transition-colors"
            >
              查看更多记录 ({totalCategoryCount - showLimit})
            </a>
          </div>
        )}
      </div>
    </div>
  );
}; 

export default TaskHistory